const express = require('express')
const multer = require('multer')
const config = require(process.cwd() + '/src/config/config')
const fileUtils = require(process.cwd() + '/src/utils/file')
const tiles = require(process.cwd() + '/src/utils/tiles')

let router = express.Router()

// 通过 filename 属性定制
var storage = multer.diskStorage({
  // 保存的路径，备注：需要自己创建
  destination (req, file, callback) {
    const name = fileUtils.cutFileTail(file.originalname)
    const path = config.autotilesPath + name + '/'
    fileUtils.createFolder(path).then(() => {
      callback(null, path)
    })
    .catch((err) => {
      console.log(err)
    })
  },
  filename (req, file, callback) {
    // 将保存文件名设置为文件原名
    callback(null, file.originalname)
  }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })

router.post('/', upload.single('autotile'), function(req, res) {
  const nameWithoutTail = fileUtils.cutFileTail(req.file.originalname)
  const originPath = config.autotilesPath + nameWithoutTail + '/' + req.file.originalname
  tiles.addAutotile(originPath).then(() => {
    res.send(config.autotilesSrcPath + nameWithoutTail + '/' + req.file.originalname)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
    
    // 文件创建出错，删除整个路径
    fileUtils.deleteDir(config.autotilesPath + nameWithoutTail)
    .then(() => {
      console.log('已删除')
    })
    .catch((err) => {
      console.log(err)
    })
  })
})

module.exports = router
